package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BTermBrandInfo;
import cc.rengu.redp.bizimpl.upmp.dao.BTermBrandInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.BTermBrandInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service("bTermBrandInfoService")
@DS("upmp")
public class BTermBrandInfoServiceImpl extends ServiceImpl<BTermBrandInfoMapper, BTermBrandInfo> implements IBTermBrandInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private BTermBrandInfoMapper bTermBrandInfoMapper;
    @Autowired
    private IUpmpSysSeqService sysSeqService;
    @Autowired
    private IBTermModelInfoService modelInfoService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;


    private long oprMenuId = 1;
    private String oprMenuName = "终端管理:终端品牌管理";
    private long chkMenuId = 2;
    private String chkMenuName = "终端管理:终端品牌审核";
    private String webNextUrl = "/terminalAdmin";


    @Override
    public IPage<BTermBrandInfo> findByPage(QueryRequest request, BTermBrandInfo brand) {
        try {
            LambdaQueryWrapper<BTermBrandInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(brand.getInstId())) {
                queryWrapper.eq(BTermBrandInfo::getInstId, brand.getInstId()).orderByDesc(BTermBrandInfo::getBrandCode);
            }
            if (!StringUtils.isEmpty(brand.getBrandCode())) {
                queryWrapper.and(i -> i.like(BTermBrandInfo::getBrandCode, brand.getBrandCode())
                        .or().like(BTermBrandInfo::getBrandName, brand.getBrandName())
                        .or().like(BTermBrandInfo::getBrandDesc, brand.getBrandDesc())).orderByDesc(BTermBrandInfo::getBrandCode);
            }

            Page<BTermBrandInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);

            //设置模型数量
            Page<BTermBrandInfo> brandInfoPage = this.page(page, queryWrapper);

            for (BTermBrandInfo record : brandInfoPage.getRecords()) {
                int num = modelInfoService.countModel(record.getBrandCode());
                record.setModelNum(num);
            }
            return brandInfoPage;
        } catch (Exception e) {
            log.error("获取品牌信息失败", e);
            return null;
        }
    }

    @Override
    public void createBrand(BTermBrandInfoVO brand) throws RedpException {
        saveData(brand);
    }

    /**
     * 校验终端品牌编码是否存在
     *
     * @param brandcd
     * @return
     */
    private boolean checkBrandCodeExist(String brandcd) {
        LambdaQueryWrapper<BTermBrandInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTermBrandInfo::getBrandCode, brandcd);
        int count = this.count(queryWrapper);
        if (count != 0) {
            //存在返回
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void updateBrand(BTermBrandInfoVO brand) throws RedpException {
        saveData(brand);
    }

    private void saveData(BTermBrandInfoVO entity) throws RedpException {
        String flag = entity.getOptFlag();
        String id = entity.getId();
        String brandName = entity.getBrandName();
        String brandCode = entity.getBrandCode();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        BTermBrandInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            oldEntity = baseMapper.selectById(id);
        }
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {

            entity.setId(null);
            boolean result = count(brandName);
            if (!result) {
                String message = "终端品牌名重复,请重新填写";
                log.error(message);
                throw new RedpException(message);
            }

            //获取品牌代码
            brandCode = BusinessContainer.BrandCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                    .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.BrandCd_PREFIX, null)));

            if (checkBrandCodeExist(brandCode)) {
                String message = "终端品牌代码重复,联系管理员";
                log.error(message);
                throw new RedpException(message);
            } else {
                entity.setBrandCode(brandCode);
            }
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "brand:add");

            BTermBrandInfo newBrand = new BTermBrandInfo();
            BeanUtils.copyProperties(entity, newBrand);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                newBrand.setOprId(user.getId());
                newBrand.setCreateTime(lastUpddt);
                newBrand.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                newBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());

                this.save(newBrand);

                bizTmpService.saveBizTmp(newBrand, user, user.getId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, newBrand.getStatus(), newBrand.getAuditStatus(), String.valueOf(newBrand.getId()), webNextUrl, null, null, null);

            } else {
                //不需要审核
                newBrand.setOprId(user.getId());
                //       entity.setCrtOrgId(org.getOrgCode());
                newBrand.setCreateTime(lastUpddt);
                newBrand.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                newBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(newBrand);

                bizHisService.saveBizHisNew(newBrand, newBrand, user, user.getId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, String.valueOf(newBrand.getId()), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            if (!oldEntity.getBrandName().equals(brandName)) {
                boolean result = count(entity.getBrandName());
                if (!result) {
                    String message = "终端品牌名重复,请重新填写!";
                    log.error(message);
                    throw new RedpException(message);
                }
            }

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "brand:edit");

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                entity.setLastOprId(user.getId());
                entity.setLastUpdateTime(lastUpddt);
                BTermBrandInfo newBrand = new BTermBrandInfo();
                BeanUtils.copyProperties(entity, newBrand);
                this.saveOrUpdate(newBrand);//只修改状态

                bizTmpService.saveBizTmp(newBrand, user, user.getId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, newBrand.getStatus(), newBrand.getAuditStatus(), String.valueOf(newBrand.getId()), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                entity.setLastOprId(user.getId());
                entity.setLastUpdateTime(lastUpddt);
                BTermBrandInfo termBrand = baseMapper.selectById(id);
                BeanUtils.copyProperties(entity, termBrand);
                this.saveOrUpdate(termBrand);

                bizHisService.saveBizHisNew(termBrand, oldEntity, user, user.getId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, String.valueOf(termBrand.getId()), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            BTermBrandInfo termBrandNew = JSON.parseObject(bizdata, BTermBrandInfo.class);

            BTermBrandInfo termBrand = baseMapper.selectById(id);
            // 备份正式表数据
            BTermBrandInfo termBrandOld = new BTermBrandInfo();
            BeanUtils.copyProperties(termBrand, termBrandOld);
            if (Common.isBlank(termBrand)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }
            //校验终端品牌名称不能重复
            if ("pass".equals(opt)) {
                boolean result = count(termBrandNew.getBrandName());
                if (!result) {
                    String message = "终端品牌名重复,请审核拒绝退回重新修改!";
                    log.error(message);
                    throw new RedpException(message);
                }
            }
            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termBrand.getAuditStatus())) {
                if (!PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {

                } else {
                    BeanUtils.copyProperties(termBrandNew, termBrand);
                }
            } else {
                BeanUtils.copyProperties(termBrandNew, termBrand);
            }

            String auditRefuseReason = entity.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(termBrand.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    termBrand.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    termBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termBrand.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    termBrand.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    termBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            termBrand.setAuditRefuseReason(auditRefuseReason);
            this.save(termBrand);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(termBrand, termBrandOld, user, user.getId(), bizOpr, lastUpddt
                        , String.valueOf(chkMenuId), chkMenuName, String.valueOf(termBrand.getId()), null, null, null);
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(termBrand, user, user.getId(), bizOpr, lastUpddt, String.valueOf(chkMenuId), chkMenuName, termBrand.getStatus(), termBrand.getAuditStatus(), String.valueOf(termBrand.getId()), webNextUrl, null, null, null);
        }

    }

    @Override
    public boolean count(String brandName) {
        LambdaQueryWrapper<BTermBrandInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTermBrandInfo::getBrandName, brandName);
        int count = this.count(queryWrapper);
        if (count != 0) {
            //存在返回
            return false;
        } else {
            return true;
        }

    }

    @Override
    public List<BTermBrandInfo> findTests() {
        try {
            return baseMapper.selectList(new QueryWrapper<BTermBrandInfo>().orderByDesc("CREATE_TIME"));
        } catch (Exception e) {
            log.error("获取信息失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public void batchInsert(List<BTermBrandInfoVO> list) throws RedpException {
        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(list.get(0).getInstId(), "brand:add");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {

            for (int i = 0; i < list.size(); i++) {
                BTermBrandInfo newBrand = new BTermBrandInfo();
                BeanUtils.copyProperties(list.get(i), newBrand);
                //获取品牌代码
                String brandcd = BusinessContainer.BrandCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                        .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.BrandCd_PREFIX, null)));

                newBrand.setBrandCode(brandcd);
                newBrand.setCrtOrgId(user.getCrtOrgId());
                newBrand.setOprId(user.getId());
                newBrand.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                newBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(newBrand);

                bizTmpService.saveBizTmp(newBrand, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        newBrand.getStatus(), newBrand.getAuditStatus(), newBrand.getId(), "", null, null, null);
            }

        } else {
//            List<BTermBrandInfo> insertList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                BTermBrandInfo newBrand = new BTermBrandInfo();
                BeanUtils.copyProperties(list.get(i), newBrand);
                //获取品牌代码
                String brandcd = BusinessContainer.BrandCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                        .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.BrandCd_PREFIX, null)));

                newBrand.setBrandCode(brandcd);
                newBrand.setCrtOrgId(user.getCrtOrgId());
                newBrand.setOprId(user.getId());
                newBrand.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                newBrand.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(newBrand);

                bizHisService.saveBizHisNew(newBrand, newBrand, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        newBrand.getId(), null, null, null);
            }
        }
    }

    @Override
    public List<BTermBrandInfo> getBrandCode(String instId) {
        return bTermBrandInfoMapper.getAllBrandCode(instId);
    }

    @Override
    public Map<String, Object> termbrandSelect2List(String q, QueryRequest request) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String brandCodeOrName = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            brandCodeOrName = param[0];
        }
        String instId = "";
        if (null != param && param.length > 1) {
            if (Common.isNotBlank(param[1])) {
                instId = param[1];
            }
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(instId)) {
            instId = user.getInstId();
        }
        try {
            LambdaQueryWrapper<BTermBrandInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BTermBrandInfo::getStatus, "01");
            queryWrapper.eq(BTermBrandInfo::getInstId, instId);
            if (null != user && !user.isAdmin()) {
//                queryWrapper.in(BTermBrandInfo::getSignInstId, Arrays.asList(GZIPUtils.uncompressToString(user.getUserOrgCodes()).split(",")));
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(brandCodeOrName)) {
                String finalbrandCodeOrName = brandCodeOrName;
                queryWrapper.and(qw -> qw.likeRight(BTermBrandInfo::getBrandCode, finalbrandCodeOrName).or().likeRight(BTermBrandInfo::getBrandName, finalbrandCodeOrName));
            }
            queryWrapper.orderByDesc(BTermBrandInfo::getCreateTime);
            Page<BTermBrandInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<BTermBrandInfo> page1 = this.page(page, queryWrapper);
            List<BTermBrandInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    BTermBrandInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getBrandCode());
                    map.put("name", org.getBrandName());
                    map.put("desc", org.getBrandDesc());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取终端品牌信息失败", e);
            return null;
        }
    }

    @Override
    public BTermBrandInfo getBrandCodeAndName(String brandCode) {
        return bTermBrandInfoMapper.getBrandCodeAndName(brandCode);
    }

    @Override
    public BTermBrandInfo findTermBrand(String brandCode) {
        LambdaQueryWrapper<BTermBrandInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTermBrandInfo::getBrandCode, brandCode);
        return baseMapper.selectOne(queryWrapper);
    }


}
